package com.example.controller;

import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;

import com.example.dao.Location;
import com.example.dao.PersonForMongDao;
import com.example.dao.PersonForMongoDB;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DataControllerForMongoDB {
	
	@Autowired
	PersonForMongDao personRepository;
	
	@RequestMapping("/save")
	public PersonForMongoDB save(){
		PersonForMongoDB  p = new PersonForMongoDB("qiuxm",32);
		Collection<Location> locations =  new LinkedHashSet<Location>();
		Location loc1 = new Location("上海","2009");
		Location loc2 = new Location("合肥","2010");
		Location loc3 = new Location("广州","2011");
		Location loc4 = new Location("马鞍山","2012");
		locations.add(loc1);
		locations.add(loc2);
		locations.add(loc3);
		locations.add(loc4);
		p.setLocationCollections(locations);
		
		return personRepository.save(p);
	}

	//http://localhost:8080/q1?name=wyf
	@RequestMapping("/q1")
	public PersonForMongoDB q1(String name){

		System.out.println(name);
		PersonForMongoDB byName = personRepository.findByName(name);

		if(byName!=null){
			ObjectId objectId = new ObjectId(byName.getId());

			System.out.println("objectId's time = " + objectId.getTimestamp());
		}else {
			System.out.println("is null");
		}

		return byName;
	}

	//http://localhost:8080/q2?age=32
	@RequestMapping("/q2")
	public List<PersonForMongoDB> q2(Integer age){
		return personRepository.withQueryFindByAge(age);
	}

}
